package com.litidea.actions;

import static com.litidea.commons.keys.MailKeys.MAIL_SUBJECT_REQUEST_FINISHED;
import static com.litidea.commons.keys.MailKeys.MAIL_SUBJECT_REQUEST_REJECTED;
import static com.litidea.commons.keys.MailKeys.MAIL_SUBJECT_REQUEST_REJECTED_APPROVE_DEPLOY;
import static com.litidea.commons.keys.MailKeys.MAIL_SUBJECT_REQUEST_REJECTED_VERIFY_RULE;
import static com.litidea.commons.keys.MailKeys.MAIL_SUBJECT_REQUEST_WAITING_FOR_ALERT;
import static com.litidea.commons.keys.MailKeys.MAIL_SUBJECT_REQUEST_WAITING_FOR_APPROVE_DEPLOY;
import static com.litidea.commons.keys.MailKeys.MAIL_SUBJECT_REQUEST_WAITING_FOR_APPROVE_VERIFY_RULE;
import static com.litidea.commons.keys.MailKeys.MAIL_SUBJECT_REQUEST_WAITING_FOR_ASSIGN;
import static com.litidea.commons.keys.MailKeys.MAIL_SUBJECT_REQUEST_WAITING_FOR_COMFIRM_EVA;
import static com.litidea.commons.keys.MailKeys.MAIL_SUBJECT_REQUEST_WAITING_FOR_DEPLOY;
import static com.litidea.commons.keys.MailKeys.MAIL_SUBJECT_REQUEST_WAITING_FOR_EVALUATION;
import static com.litidea.commons.keys.MailKeys.MAIL_SUBJECT_REQUEST_WAITING_FOR_SET_VERIFY_RULE;
import static com.litidea.commons.keys.MailKeys.MAIL_SUBJECT_WAITING_FOR_DEPARTMENT_APPROVE;
import static com.litidea.commons.keys.MailKeys.MAIL_TEXT_WAITING_FOR_DEPARTMENT_APPROVE;
import static com.litidea.commons.keys.SystemKeys.ATTACHMENTS_UPLOAD_URL;
import static com.litidea.commons.keys.SystemKeys.PUB_ADD_OPTION;
import static com.litidea.commons.keys.SystemKeys.PUB_DEL_OPTION;
import static com.litidea.commons.keys.SystemKeys.PUB_EDIT_OPTION;
import static com.litidea.commons.keys.SystemKeys.REPORT_UPLOAD_URL;
import static com.litidea.commons.paramkeys.BasicDataParamKeys.SAVE_CHANGE_TYPE_TEST_ITEMS_PARAMS;
import static com.litidea.commons.paramkeys.ChangeParamKeys.SAVE_INTERNAL_CHANGE_DATE_PARAMS;
import static com.litidea.commons.paramkeys.ChangeParamKeys.SAVE_INTERNAL_CHANGE_EVA_PARAMS;
import static com.litidea.commons.paramkeys.ChangeParamKeys.SAVE_INTERNAL_CHANGE_NOTIFICATION_DATE_PARAMS;
import static com.litidea.commons.paramkeys.ChangeParamKeys.SAVE_INTERNAL_CHANGE_NOTIFICATION_PARAMS;
import static com.litidea.commons.paramkeys.ChangeParamKeys.SAVE_INTERNAL_CHANGE_NOTIFICATION_USERS_PARAMS;
import static com.litidea.commons.paramkeys.ChangeParamKeys.SAVE_INTERNAL_CHANGE_PARAMS;

import java.util.List;
import java.util.Map;

import com.litidea.dao.InternalChangeDAO;
import com.litidea.dataobjects.ChangeTypeTestItemsDO;
import com.litidea.dataobjects.UserLoginDO;
import com.opensymphony.xwork2.Action;

public class InternalChangeManageAction extends BaseAction implements Action {
	/**
	 * 序列码
	 */
	private static final long serialVersionUID = 968674751758541095L;

	private InternalChangeDAO changeDAO;

	/**
	 * 获取产品列表
	 * 
	 * @return
	 */
	public String getInternalChanges() {
		Map<String, String> params = getParameters(SAVE_INTERNAL_CHANGE_PARAMS);
		try {
			fillPageParams(params);

			// 需要根据登录人的权限返回列表，需跟客户确认。
			// 1. 普通用户只能看到自己提的申请
			// 2. 部门领导可以看到自己部门的申请
			// 3. 验证人员可以看到需要自己验证的申请
			// 4. 是否需要处理完就不可看见了

			return responseAjax(changeDAO.getInternalChangePageList(params)
					.toString());
		} catch (Exception e) {
			errorInfo = e.getMessage();
		}
		return null;
	}

	/**
	 * 编辑内部变更
	 * 
	 * @return
	 */
	public String saveInternalChange() {
		Map<String, String> params = getParameters(SAVE_INTERNAL_CHANGE_PARAMS);
		String success = null, errorInfo = null;
		try {
			int type = Integer.valueOf(params.get("type"));
			switch (type) {
			case PUB_ADD_OPTION:
				// 添加操作人员信息
				UserLoginDO userDO = this.findUserInfo();
				params.put("appliedUserId", String.valueOf(userDO.getId()));
				params.put("appliedDeptId", String.valueOf(userDO.getDeptId()));

				// 获取评审部门信息
				/*
				 * String deptId = params.get("evaDeptId"); DepartmentDO
				 * departmentDO = this.systemDAO .getDepartMentById(deptId);
				 * 
				 * if (departmentDO.getDeptMgr() == 0) throw new
				 * RuntimeException("部门领导还没设置！"); params.put("evaDeptMgrId",
				 * String.valueOf(departmentDO .getDeptMgr()));
				 */
				
				// 上传附件
				// 上传附件
				String saveFileFullName = this.saveUploadFile(ATTACHMENTS_UPLOAD_URL);
				params.put("appliedAttachment", saveFileFullName);
				
				if("".equals(params.get("effectiveStartDate"))){
					params.put("effectiveStartDate", null);
				}
				if("".equals(params.get("effectiveEndDate"))){
					params.put("effectiveEndDate", null);
				}

				// 邮件通知-科长批准
				String requestId = String.valueOf(changeDAO
						.addNewInternalChange(params));
				this.emailNotification(requestId, params.get("approvedMgrId"),
						MAIL_SUBJECT_WAITING_FOR_DEPARTMENT_APPROVE,
						MAIL_TEXT_WAITING_FOR_DEPARTMENT_APPROVE);

				success = "添加内部变更成功";

				break;
			case PUB_EDIT_OPTION:
				success = changeDAO.editInternalChange(params);
				break;
			case PUB_DEL_OPTION:
				Integer id = Integer.valueOf(params.get("id"));
				success = changeDAO.deleteInternalChange(id);
				break;
			}
		} catch (Exception e) {
			errorInfo = e.getMessage();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 编辑内部变更
	 * 
	 * @return
	 */
	public String createInternalChange() {
		Map<String, String> params = getParameters(SAVE_INTERNAL_CHANGE_PARAMS);
		String success = null, errorInfo = null;
		try {
			// 添加操作人员信息
			UserLoginDO userDO = this.findUserInfo();
			params.put("appliedUserId", String.valueOf(userDO.getId()));
			params.put("appliedDeptId", String.valueOf(userDO.getDeptId()));

			if("".equals(params.get("effectiveStartDate"))){
				params.put("effectiveStartDate", null);
			}
			if("".equals(params.get("effectiveEndDate"))){
				params.put("effectiveEndDate", null);
			}
			
			// 上传附件
			String saveFileFullName = this.saveUploadFile(ATTACHMENTS_UPLOAD_URL);
			params.put("appliedAttachment", saveFileFullName);
			
			// 邮件通知-科长批准
			String requestId = String.valueOf(changeDAO
					.createNewInternalChange(params));
			this.emailNotification(requestId, params.get("approvedMgrId"),
					MAIL_SUBJECT_WAITING_FOR_DEPARTMENT_APPROVE,
					MAIL_TEXT_WAITING_FOR_DEPARTMENT_APPROVE);

			success = "添加内部变更成功";
		} catch (Exception e) {
			errorInfo = e.getMessage();
			e.printStackTrace();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 批准内部变更
	 * 
	 * @return
	 */
	public String approveInternalChange() {
		Map<String, String> params = getParameters(SAVE_INTERNAL_CHANGE_PARAMS,
				SAVE_INTERNAL_CHANGE_DATE_PARAMS);
		String success = null, errorInfo = null;
		try {
			// 添加操作人员信息
			UserLoginDO userDO = this.findUserInfo();
			params.put("approvedMgrId", String.valueOf(userDO.getId()));
			success = changeDAO.approveInternalChange(params);

			// 邮件通知--验证科室科长组织验证人员
			String text = "新的变更等待您批准下发。";
			this.emailNotification(params.get("id"),
					params.get("evaDeptMgrId"),
					MAIL_SUBJECT_REQUEST_WAITING_FOR_ASSIGN, text);

		} catch (Exception e) {
			errorInfo = e.getMessage();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 拒绝内部变更
	 * 
	 * @return
	 */
	public String rejectInternalChange() {
		Map<String, String> params = getParameters(SAVE_INTERNAL_CHANGE_PARAMS,
				SAVE_INTERNAL_CHANGE_DATE_PARAMS);
		String success = null, errorInfo = null;
		try {
			// 添加操作人员信息
			UserLoginDO userDO = this.findUserInfo();
			params.put("rejectedBy", String.valueOf(userDO.getId()));
			success = changeDAO.rejectInternalChange(params);

			// 邮件通知--申请人
			String text = "您申请的变更请求被科长拒绝。拒绝理由：" + params.get("rejectedReason");

			this.emailNotification(params.get("id"), params
					.get("appliedUserId"), MAIL_SUBJECT_REQUEST_REJECTED, text);

		} catch (Exception e) {
			errorInfo = e.getMessage();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 设置验证组
	 * 
	 * @return
	 */
	public String setVerifyTeam() {
		Map<String, String> params = getParameters(SAVE_INTERNAL_CHANGE_PARAMS);
		String success = null, errorInfo = null;
		try {
			success = changeDAO.setVerifyTeam(params);

			// 邮件通知--验证科室科长组织验证人员
			String text = "新的变更等待您设置验证规则。";
			this.emailNotification(params.get("id"), params.get("evaLeader"),
					MAIL_SUBJECT_REQUEST_WAITING_FOR_SET_VERIFY_RULE, text);
		} catch (Exception e) {
			errorInfo = e.getMessage();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 判定变更类别和阶段
	 * 
	 * @return
	 */
	public String setChangeType() {
		Map<String, String> params = getParameters(SAVE_INTERNAL_CHANGE_PARAMS);
		String success = null, errorInfo = null;
		try {
			success = changeDAO.setChangeType(params);
		} catch (Exception e) {
			errorInfo = e.getMessage();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 查看变更类型的实验项目
	 * 
	 * @return
	 */
	public String viewChangeTypeTestItems() {
		Integer id = getInt("id");
		List<ChangeTypeTestItemsDO> list = changeDAO
				.getTestItemssByChangeId(id);
		return responseAjax(list);
	}

	/**
	 * 更新可选必选
	 * 
	 * @return
	 */
	public String updateIsMust() {
		Map<String, String> params = this
				.getParameters(SAVE_CHANGE_TYPE_TEST_ITEMS_PARAMS);
		String success = "操作成功。", errorInfo = null;
		try {
			changeDAO.updateIsMust(params);
		} catch (Exception e) {
			errorInfo = e.toString();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 提交变更测试计划
	 * 
	 * @return
	 */
	public String submitForTestPlanApproval() {
		Map<String, String> params = this
				.getParameters(SAVE_INTERNAL_CHANGE_PARAMS);
		String success = "操作成功。", errorInfo = null;
		try {
			changeDAO.submitForTestPlanApproval(params);

			// 邮件通知-备选的审批者进行审批
			String text = "新的变更，验证计划设置完毕。等待您审批验证规则。";
			this.emailNotification(params.get("id"), params
					.get("testPlanApprover"),
					MAIL_SUBJECT_REQUEST_WAITING_FOR_APPROVE_VERIFY_RULE, text);
		} catch (Exception e) {
			errorInfo = e.toString();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 批准验证计划
	 * 
	 * @return
	 */
	public String approveTestPlan() {
		Map<String, String> params = this
				.getParameters(SAVE_INTERNAL_CHANGE_PARAMS);
		String success = "操作成功。", errorInfo = null;
		try {
			params.put("status", "7");
			/*
			 * // 判断下一个状态
			 * if(params.get("mustAlertCustomer").equals("2")&&params.get("mustSpplierChange").equals("2"))
			 * params.put("status", "9"); else params.put("status", "8");
			 */
			changeDAO.approveTestPlan(params);

			// 邮件通知
			String text = "新的变更，验证计划审批完毕。等待您评审。";
			this.emailNotification(params.get("id"), params.get("evaLeader"),
					MAIL_SUBJECT_REQUEST_WAITING_FOR_EVALUATION, text);
		} catch (Exception e) {
			errorInfo = e.toString();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 拒绝验证计划
	 * 
	 * @return
	 */
	public String rejectTestPlan() {
		Map<String, String> params = this
				.getParameters(SAVE_INTERNAL_CHANGE_PARAMS);
		String success = "操作成功。", errorInfo = null;
		try {
			changeDAO.rejectTestPlan(params);

			// 邮件通知
			String text = "新的变更，验证计划审批被拒绝。请重新设置验证计划。";
			this.emailNotification(params.get("id"), params.get("evaLeader"),
					MAIL_SUBJECT_REQUEST_REJECTED_VERIFY_RULE, text);
		} catch (Exception e) {
			errorInfo = e.toString();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 保存变更评审
	 * 
	 * @return
	 */
	public String saveChangeEvaluation() {
		Map<String, String> params = getParameters(SAVE_INTERNAL_CHANGE_EVA_PARAMS);
		String success = null, errorInfo = null;
		try {
			// 上传验证报告
			/*
			 * String saveFileFullName = this.saveUploadFile(REPORT_UPLOAD_URL);
			 * params.put("resultReportUrl", saveFileFullName);
			 */

			// 判断是拒绝还是同意
			if (params.get("result").equals("1")) {
				/*
				 * // 同意 params.put("status", "5"); // 如果不需要验证，就跳过上传验证报告
				 * if(params.get("mustVerify").equals("2")){
				 * if(params.get("mustAlertCustomer").equals("2")&&params.get("mustSpplierChange").equals("2"))
				 * params.put("status", "9"); else params.put("status", "8"); }
				 */
			} else {
				// 拒绝
				// 添加操作人员信息
				UserLoginDO userDO = this.findUserInfo();
				params.put("rejectedBy", String.valueOf(userDO.getId()));
				params.put("status", "15");
			}
			success = changeDAO.saveChangeEvaluation(params);
		} catch (Exception e) {
			errorInfo = e.getMessage();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 上传测试报告
	 * 
	 * @return
	 */
	public String uploadResultReport() {
		Map<String, String> params = getParameters(SAVE_INTERNAL_CHANGE_EVA_PARAMS);
		String success = null, errorInfo = null;
		try {
			// 上传验证报告
			String saveFileFullName = this.saveUploadFile(REPORT_UPLOAD_URL);
			params.put("resultReportUrl", saveFileFullName);

			// 添加操作人员信息
			UserLoginDO userDO = this.findUserInfo();
			params.put("rejectedBy", String.valueOf(userDO.getId()));

			success = changeDAO.uploadResultReport(params);
		} catch (Exception e) {
			errorInfo = e.getMessage();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 结束上传验证报告
	 * 
	 * @return
	 */
	public String finishUploadReport() {
		Map<String, String> params = getParameters(SAVE_INTERNAL_CHANGE_EVA_PARAMS);
		String success = null, errorInfo = null;
		try {
			// 如果需要通报客户则发邮件通知下一个处理人
			// 邮件通知
			if (params.get("qualityDeptUser") != null) {
				String text = "新的变更，变更单已评审完毕等待通报客户。";
				this.emailNotification(params.get("id"), params
						.get("qualityDeptUser"),
						MAIL_SUBJECT_REQUEST_WAITING_FOR_ALERT, text);
			}
			success = changeDAO.finishUploadReport(params);
		} catch (Exception e) {
			errorInfo = e.getMessage();
			e.printStackTrace();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 通报客户和供应商
	 * 
	 * @return
	 */
	public String alertCustSup() {
		Map<String, String> params = getParameters(SAVE_INTERNAL_CHANGE_NOTIFICATION_PARAMS);
		String success = null, errorInfo = null;
		try {
			// 上传附件
			String saveFileFullName = this
					.saveUploadFile(ATTACHMENTS_UPLOAD_URL);
			params.put("attachmentForAlert", saveFileFullName);

			success = changeDAO.alertCustomerAndSupplier(params);

			// 邮件通知
			String text = "新的变更，变更单通报客户，等待确认评审。";
			this.emailNotification(params.get("id"), params.get("evaLeader"),
					MAIL_SUBJECT_REQUEST_WAITING_FOR_COMFIRM_EVA, text);
		} catch (Exception e) {
			errorInfo = e.getMessage();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 保存变更通知
	 * 
	 * @return
	 */
	public String saveDeployChange() {
		Map<String, String> params = getParameters(
				SAVE_INTERNAL_CHANGE_NOTIFICATION_PARAMS,
				SAVE_INTERNAL_CHANGE_NOTIFICATION_DATE_PARAMS);
		String success = null, errorInfo = null;
		try {
			success = changeDAO.saveChangeNotification(params);

			// 通知评审部门领导批准下发
			// 邮件通知
			String text = "新的变更，变更单通报客户，等待确认评审。";
			this.emailNotification(params.get("id"),
					params.get("evaDeptMgrId"),
					MAIL_SUBJECT_REQUEST_WAITING_FOR_APPROVE_DEPLOY, text);
		} catch (Exception e) {
			errorInfo = e.getMessage();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 批准验证计划
	 * 
	 * @return
	 */
	public String approveDeploy() {
		Map<String, String> params = this
				.getParameters(SAVE_INTERNAL_CHANGE_PARAMS);
		String success = "操作成功。", errorInfo = null;
		try {
			String status = params.get("status");

			UserLoginDO userLoginDO = this.findUserInfo();
			params.put("rejectedBy", String.valueOf(userLoginDO.getId()));

			changeDAO.approveTestPlan(params);

			// 邮件通知
			String text = "新的变更，下发审批完毕。等待下发执行。";
			String subject = MAIL_SUBJECT_REQUEST_WAITING_FOR_DEPLOY;
			if ("23".equals(status)) {
				text = "新的变更，下发审批被拒绝。流程结束。";
				subject = MAIL_SUBJECT_REQUEST_REJECTED_APPROVE_DEPLOY;
				this.emailNotification(params.get("id"), params
						.get("appliedUserId"), subject, text);
			}
			this.emailNotification(params.get("id"), params.get("evaLeader"),
					subject, text);
		} catch (Exception e) {
			errorInfo = e.toString();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 选择通知单下发部门和处理人员
	 * 
	 * @return
	 */
	public String selectDeployDeptUsers() {
		Map<String, String> params = getParameters(SAVE_INTERNAL_CHANGE_NOTIFICATION_USERS_PARAMS);
		String success = null, errorInfo = null;
		try {

			params.put("status", "17");

			success = changeDAO.selectDeployDeptUsers(params);
		} catch (Exception e) {
			errorInfo = e.getMessage();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 执行变更
	 * 
	 * @return
	 */
	public String deployChange() {
		String success = null, errorInfo = null;
		try {
			Map<String, String> params = getParameters(SAVE_INTERNAL_CHANGE_NOTIFICATION_PARAMS);

			// 上传附件
			String saveFileFullName = this
					.saveUploadFile(ATTACHMENTS_UPLOAD_URL);
			params.put("attachment", saveFileFullName);

			success = changeDAO.deployChange(params);
		} catch (Exception e) {
			errorInfo = e.getMessage();
			e.printStackTrace();
		}
		return normalResponse(errorInfo, success);
	}

	/**
	 * 结束流程
	 * 
	 * @return
	 */
	public String finished() {
		Map<String, String> params = getParameters(SAVE_INTERNAL_CHANGE_PARAMS);
		String success = null, errorInfo = null;
		try {
			success = changeDAO.finished(params);
			// 邮件通知
			String text = "新的变更-已完成。";
			this.emailNotification(params.get("id"), params
					.get("appliedUserId"), MAIL_SUBJECT_REQUEST_FINISHED, text);

		} catch (Exception e) {
			errorInfo = e.getMessage();
		}
		return normalResponse(errorInfo, success);
	}

	public InternalChangeDAO getChangeDAO() {
		return changeDAO;
	}

	public void setChangeDAO(InternalChangeDAO changeDAO) {
		this.changeDAO = changeDAO;
	}
}
